<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/common/taglibs.jsp" %>
<%@ taglib prefix ="s" uri="/struts-tags"%>
<%@ page import="com.starbaba.core.web.constant.WebConstants"%>
<%@ page import="com.starbaba.system.user.model.UserVO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html lang="zh-Hans">
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<head>
		<%@ include file="/common/common-css.v2.jsp" %>
		<link href="${ctx}/css/bootstrap-multiselect.css" rel="stylesheet" />
		
		<style>
		#jquery-table td{word-break: break-all;word-wrap: break-word;}
		.load_bg{background:#000;opacity:0.1;left:0px;top:0px;position:fixed;height:100%;width:100%;overflow:hidden;z-index:10000;}
		.load_img{left:50%;top:180px;position:fixed;height:50px;overflow:hidden;z-index:20000;}
		a.check{
			margin-bottom:10px;
		}
		b.caret{
			margin-top: 0 !important;
		}
		.datepicker.dropdown-menu{
			z-index: 99998 !important;
		}
		.discovery-alert {
		    position: fixed;
		    width: 300px;
		    z-index: 99999;
		    left: 50%;
		    margin-left: -150px;
		    top: 300px;
		    display: none;
		}
		ul.multiselect-container{
			max-height: 300px;
			overflow: auto;
		}
		@media (min-width: 768px) and  (max-width: 1200px){
			.backup-text{
				width:100px !important;
			}
		}
		</style>
	</head>
<body  class="no-skin">
<div  class="load_bg" style="display:none;" ></div>
<img src="http://img.xmiles.cn/commentloading.gif" class="load_img" style="display:none"/>
<div class="page-content">
<div id="test"></div>
			<div class="page-header" style="margin-bottom:0px;padding-bottom:10px;">
			
				<h1 id="fu_name">
					
				</h1>
			</div>
	<form id="queryForm" >
	<div class="page-content-area">
		<div class="row">
			<div class="col-sm-12">
				<div class="widget-box" style="border:0px solid #ccc; border-top:none;border-bottom:none;">
					<div class="widget-header widget-header-blue widget-header-flat">
						<h4 class="widget-title">选择条件进行查询</h4>

						<div class="widget-toolbar">
							<a href="#" data-action="collapse">
								<i class="ace-icon fa fa-chevron-up"></i>
							</a>
						</div>
					</div>

					<div class=" widget-body">
						<!-- <div class="widget-main" style="padding:12px;border:0px solid #ccc; border-top:none;border-bottom:none;"> -->
									<div class="widget-main clearfix" >

										<div class="form-group col-xs-12 col-sm-6 col-md-4 col-lg-4">
											<label class="col-sm-2 control-label" for="username" style="text-align:right;">用户名:</label>
											<div class="col-sm-10">
												<input type="text" class="form-control" name="username" id="username">
											</div>
										</div>
										
										
							</div><!-- /.widget-main -->
					</div><!-- /.widget-body -->
				</div><!-- /.widget-box -->
			</div><!-- /.col-sm-12 -->
				<div class="col-md-12 center">
				<div class="clearfix form-actions">
				
					<button class="btn btn-purple  no-border" type="button" name="btn-query" onclick="query_any()" id="btn-query">
						<i class="ace-icon fa fa-search icon-on-right bigger-110"></i>
						查询
					</button>
					&nbsp;&nbsp;&nbsp;
					<button class="btn btn-grey  no-border" type="reset">
						<i class="ace-icon fa fa-undo icon-on-right bigger-110"></i>
						重置
					</button>
					&nbsp;&nbsp;&nbsp;
					<a class="btn btn-grey  no-border" data-toggle="modal" data-target="#myModal">						
						添加
					</a>
				  </div>
		   </div>
		</div><!-- /.row -->
		
		<div class="row">
			<div class="col-xs-12">
				<table id="jquery-table" class="table table-striped table-bordered table-hover">
				
				</table>
			</div><!-- /.col -->
		</div><!-- /.row -->
			
	</div><!-- /.page-content-area -->
	</form>
</div><!-- /.page-content -->

<!--模态框-->
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">新增账户</h4>
      </div>
      <div class="modal-body clearfix">
	    <div class="row">
			<div class="form-group col-xs-10">
				<label class="col-sm-4 control-label"  for="userId">用户名:</label>
				<div class="input-group col-sm-8">
					<input class="form-control" name="userId" id="userId">
				</div>
			</div>
			<div class="form-group col-xs-10">
				<label class="col-sm-4 control-label"  for="trueName">真实姓名:</label>
				<div class="input-group col-sm-8">
					<input type="text" class="form-control" name="trueName" id="trueName">
				</div>
			</div>
			<div class="form-group col-xs-10">
				<label class="col-sm-4 control-label"  for="stopdate">到期时间:</label>
				<div class="input-group col-sm-8">
					<input type="text" data-date-format="yyyy-mm-dd" class="date-picker form-control" name="stopdate" id="stopdate" placeholder="默认有效期100年">
				</div>
			</div>
			<div class="form-group col-xs-10">
				<label class="col-sm-4 control-label"  for="password">密码:</label>
				<div class="input-group col-sm-8">
					<input type="password" class="form-control" name="password" id="password">
				</div>
			</div>
			<div class="form-group col-xs-10">
				<label class="col-sm-4 control-label"  for="password-confirm">确认密码:</label>
				<div class="input-group col-sm-8">
					<input type="password" class="form-control" name="password-confirm" id="password-confirm">
				</div>
			</div>
			<div class="form-group col-xs-10">
				<label class="col-sm-4 control-label"  for="add-user-access">组别权限:</label>
				<div class="input-group col-sm-8">
					<select class="form-control" name="add-user-access" id="add-user-access" multiple="multiple">
					</select>
				</div>
			</div>
		</div>		
       	   
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="button" class="btn btn-primary" id="addUser">确认</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<!--模态框-->
<div class="modal fade" id="myModal-change">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">用户组别修改</h4>
      </div>
      <div class="modal-body clearfix">
	    <div class="row">
			<div class="form-group col-xs-12">
				<label class="col-sm-2 control-label"  for="change-user-access">用户组别:</label>
				<div class="input-group col-sm-6">
					<select class="form-control" name="change-user-access" id="change-user-access" multiple="multiple">
					</select>
				</div>
			</div>
		</div>			
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

<!--警告-->
<div class="alert alert-danger alert-dismissible discovery-alert" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  <span id="alert-text"></span>
</div>

<!--获取userid-->
<div id="getCreator" class="hidden"><cx:Code2Name definition="!com.starbaba.system.user.model.UserVO*username*userid" value="<%= ((UserVO) session.getAttribute(WebConstants.SESSION_ATTRIBUTE_USER)).getUserid() %>"/></div>

<%@ include file="/common/common-js.jsp" %>
<script type="text/javascript" src="${ctx}/js/call_func.js"></script>
<script type="text/javascript" src="${ctx}/js/bootstrap-multiselect.js"></script>
<!-- inline scripts related to this page -->
<script type="text/javascript">
	
//定义参数
var creator = $('#getCreator').text();
var userGroup = 0;
var userAccess = [];
var allUserGroup = [];
var insertHtml = '';

//接受URL参数，进行文档写入
function getQueryString(name) {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
	var r = window.location.search.substr(1).match(reg);
	if (r != null) return decodeURI(r[2]); return null;
}

function toast(text, selector){
	$('#alert-text').text(text);
	$('.discovery-alert').show();
	if(selector != '' && selector != null){
		$(selector).focus();
	};
	setTimeout(function(){
		$('.discovery-alert').hide();
	},3000);
};

//【查询】按钮Click事件
function query_any(){
	if(jqTable != null){
		jqTable.fnDraw();
		
	}else{
		loaddata();	
	}
}
          
var jqTable = null;
var loaddata = function(){
	jQuery(function($) {
		jqTable = $('#jquery-table').dataTable( {
		    //数据列控制（包括对应返回JSON属性名称，对应表头列索引位置、数据转换封装等）
		    "columnDefs": [
		    	{	  
		    		  "title":'账户名',
		    	  	  "targets": [0],
					  "data": "userid",   //JSON返回属性
		    	  	  "class": "center",
		    	  	  "bSortable": false,
					  "width": "25%"
		    	},
				{	  
		    		  "title":'用户名',
		    	  	  "targets": [1],
					  "data": "username",   //JSON返回属性
		    	  	  "class": "center",
		    	  	  "bSortable": false,
					  "width": "25%"
		    	},
				{	  
		    		  "title":'到期时间',
		    	  	  "targets": [2],
					  "data": "stopdate",   //JSON返回属性
		    	  	  "class": "center",
		    	  	  "bSortable": false,
					  "width": "25%"
		    	},
 
				{	  
		    		  "title":'操作',
		    	  	  "targets": [3],
					  "data": "comid",   //JSON返回属性
		    	  	  "class": "center",
		    	  	  "bSortable": false,
					  "width": "25%",
					  "render": function(value, type, row) { // 返回自定义内容
							       return "<a class='btn btn-primary btn-change' data-id='"+value+"' data-userid='" + row.userid + "' data-comid='" + row.comid + "'>修改组别</a> &nbsp; <a class='btn btn-danger btn-delete' data-userid='"+row.userid+"'>注销</a>";									 
					  },
		    	},
		  	],
			"sAjaxSource": ctx+"/system/user/userListRequest.action",//数据源URL
			"fnServerData": function ( sSource, aoData, fnCallback ) {//从服务器请求数据
		   			var data = $('#queryForm').serializeObject();
					data.aoData = JSON.stringify(aoData);
					$.ajax({
						"type": "POST",
						"dataType": 'json',
						"url": sSource,
						"data": data,
						"beforeSend": function(){
							$(".load_bg,.load_img").show();
						},
						"success": function(resp){
                            console.log(resp);							
							fnCallback(resp);
							initListPage();
						},
						"error": function(XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
						},
						"complete": function(){
							$(".load_bg,.load_img").hide();
						}
				});
			},
			"sScrollXInner": "100%",
			"sScrollY": "100%",//如果不设置，IE会有问题
		    "aaSorting": [[0,"asc"]], //初始化加载，默认按第几列排序、排序方式（列从0开始计算）
		});
	});
};
	
jQuery(function($) {
	
	$(".date-picker").datepicker({autoclose:true}).next().on(ace.click_event, function(){
		$(this).prev().focus();
	});
	
	//请求获取全部用户组别
	$.ajax({
		"type": "POST",
		"dataType": 'json',
		"url": ctx+"/system/usergroup/userGroupList.action",
		"data": {},
		"beforeSend": function(){
			$(".load_bg,.load_img").show();
		},
		"success": function(resp){
			console.log("全部用户组别:" , resp);	
			allUserGroup = resp.aaData;
			$.each(allUserGroup, function(index, item){
				$('#add-user-access').append('<option value=' + item.groupid + '>' + item.groupname + '</option>');
			});
			//初始化multiselect
			$('#add-user-access').multiselect({
				noneSelectedText: "请选择", 
				allSelectedText: "已选择",
				selectedList: 30,
				onChange: function(option, checked, select) {
					canSelectOtherGroup('#add-user-access', false, null, null, null, null);
				}
			});
		},
		"error": function(XMLHttpRequest, textStatus, errorThrown) {
			alert(textStatus);
		},
		"complete": function(){
			$(".load_bg,.load_img").hide();
		}
	});
	

	//修改权限点击事件
	$(document).delegate('.btn-change', 'click', function(){
		var $this = $(this);
		var thisUserGroupId = '';
		var thisUserGroup = [];
		var userid = $(this).attr('data-userid');
		var comid = $(this).attr('data-comid');
		//清空下拉框
		$('#change-user-access').html('');
		
		//请求获取当前用户组别(by userid)
		$.ajax({
			"type": "POST",
			"dataType": 'json',
			"url": ctx+"/system/userofgroup/userOfGroupList.action",
			"data": {"userid": userid},
			"success": function(resp){	
                $.each(resp.aaData, function(index, item){
					if(index == 0){
						thisUserGroupId += item.groupid;
					}else{
						thisUserGroupId += '#' + item.groupid;
					}
				});
                console.log("当前用户组id(String--split by #):", thisUserGroupId);
				
				//嵌套请求获取当前用户组别(by thisUserGroupId)
				$.ajax({
					"type": "POST",
					"dataType": 'json',
					"url": ctx+"/system/usergroup/userGroupList.action",
					"data": {"thisUserGroupId": thisUserGroupId, "suittype": 1},
					"success": function(resp){
                        //清空						
					    insertHtml = '';
						var isManager = false;
						//取消绑定multiselect
						$('#change-user-access').multiselect('destroy');
						//循环当前用户组别,确认是否管理员
						$.each(resp.aaData, function(index, item){
							if(item.groupid == 1){
								isManager = true;
								return false;
							};
						});
					    //循环全部用户组别
						$.each(allUserGroup, function(index, item){
							insertHtml += '<option value=' + item.groupid;
							$.each(resp.aaData, function(_index, _item){
								if(isManager){
									if(item.groupid == 1){
										insertHtml += ' selected';
									}else{
										insertHtml += ' disabled';
									};
								}else{
									if(item.groupid == _item.groupid){
										insertHtml += ' selected';
									};
								}
							});
							insertHtml += '>' + item.groupname + '</option>';
						    $('#change-user-access').append(insertHtml);
							//清空
							insertHtml = '';
						});
						
						//初始化multiselect
						$('#change-user-access').multiselect({
							noneSelectedText: "请选择", 
							allSelectedText: "已选择",
							selectedList: 30,
							onChange: function(option, checked, select) {
								canSelectOtherGroup('#change-user-access', true, $(option).val(), checked, userid, comid);
							}
						});
						
						console.log("当前用户组别:", resp);				
						
						//展示模态框
						var top = $this.position().top;
						$('#myModal-change').css('top',top - 300).modal('show');
					},
					"error": function(XMLHttpRequest, textStatus, errorThrown) {
						alert(textStatus);
					}
				});
			},
			"error": function(XMLHttpRequest, textStatus, errorThrown) {
				alert(textStatus);
			}
		});
		
	});
	
	//注销账户
	$(document).delegate('.btn-delete', 'click', function(){
		var $this = $(this)
		var userid = $this.attr('data-userid');
		$.ajax({
				"type": "POST",
				"dataType": 'json',
				"url": ctx+"/system/user/deleteUser.action",
				"data": {"userid":userid},
				"beforeSend": function(){
					$(".load_bg,.load_img").show();
				},
				"success": function(resp){
					console.log(JSON.stringify(resp));
					if(resp.result.status == 1){
						//删除列
						$this.parent('td').parent('tr').remove();
					}
				},
				"error": function(XMLHttpRequest, textStatus, errorThrown){
					toast(textStatus,'');
				},
				"complete": function(){
					$(".load_bg,.load_img").hide();
				}
			});	
	})
	
	//添加用户确认按钮
	$('#addUser').on('click', function(){
		var userid = $('#userId').val();
		var truename = $('#trueName').val();
		var stopdate = $('#stopdate').val();
		var password = $('#password').val();
		var passwordConfirm = $('#password-confirm').val();
		//获取用户组的ListString
		var addUserCheckedListString = '';
		$('#add-user-access option:selected').map(function(a, item){
			if(a == 0){
			    addUserCheckedListString += item.value;
			}else{
				addUserCheckedListString += '#' + item.value;
			};
		});
		
		//用户名不允许中文
		if(userid == ''){
			toast('请输入用户名', '#userId');
		}else if(/[\u4E00-\u9FA5]/i.test(userid)){
			toast('用户名不允许中文', '#userId');
		}else if(truename == ''){
			toast('请输入真实名', '#trueName');
		}else if(password == ''){
			toast('请输入密码', '#password');
		}else if(passwordConfirm != password){
			toast('密码不一致', '#password-confirm');
		}else{
			//请求新增用户
			$.ajax({
				"type": "POST",
				"dataType": 'json',
				"url": ctx+"/system/user/addUser.action",
				"data": {"userid":userid, "username":truename, "creator": creator, "stopdate": stopdate, "password":password, "usergroup": addUserCheckedListString},
				"beforeSend": function(){
					$(".load_bg,.load_img").show();
				},
				"success": function(resp){
					console.log(JSON.stringify(resp));
					if(resp.result.status == 1){
						if(resp.result.msg == '已有同名账户'){
							toast('已有同名账户','#userId');
						}else if(resp.result.msg == '新增成功'){
							$('#myModal').modal('hide');
						}else{
							//添加成功后关闭modal并重新查询列表
							toast(resp.result.msg, '');
						}
					}
				},
				"error": function(XMLHttpRequest, textStatus, errorThrown){
					toast(textStatus,'');
				},
				"complete": function(){
					$(".load_bg,.load_img").hide();
				}
			});	
		}
		
		
	});
	
});	

//设置如果是(选择)管理员就不能选择其他组
function canSelectOtherGroup($selector, $controlData, $val, $status, $userid, $comid){
	var $list = [];
	
	$($selector + ' option:selected').map(function(a, item){
		$list.push(item.value);
	});
	
	//默认1为管理员
	if($.inArray("1",$list)>=0) {
		
		//如果选中为管理员,删除其他的数据,然后增加管理员
		if($controlData){
			if($status){
			   //先删除全部
			   $.ajax({
					"type": "POST",
					"dataType": 'json',
					"url": ctx+"/system/userofgroup/userOfGroupChange.action?type=2",
					"data": {"groupid": "1", "creator": "", "userid": $userid, "comid": $comid},
					"success": function(resp){
						console.log(JSON.stringify(resp));
						//再添加管理员
						$.ajax({
							"type": "POST",
							"dataType": 'json',
							"url": ctx+"/system/userofgroup/userOfGroupChange.action?type=1",
							"data": {"groupid": "1", "creator": creator, "userid": $userid, "comid": $comid},
							"success": function(resp){
								console.log(JSON.stringify(resp));
								
							},
							"error": function(XMLHttpRequest, textStatus, errorThrown){
								alert(textStatus);
							}
						});	
					},
					"error": function(XMLHttpRequest, textStatus, errorThrown){
						alert(textStatus);
					}
				});	
			};
		}
		
		$.each($list, function(index, item){
			if(item == "1"){
				$list.splice(index,1);
			};
		});
		
		//把其他选中的删除
		$($selector).multiselect('deselect', $list);
		
		// Disable all other checkboxes.
		var nonSelectedOptions = $($selector + ' option').filter(function() {
			return !$(this).is(':selected');
		});

		var dropdown = $($selector).siblings('.multiselect-container');
		nonSelectedOptions.each(function() {
			var input = $('input[value="' + $(this).val() + '"]');
			input.prop('disabled', true);
			input.parent('li').addClass('disabled');
		});
	}else {
		
		if($controlData){
			if($status){
				//添加当前项
				$.ajax({
					"type": "POST",
					"dataType": 'json',
					"url": ctx+"/system/userofgroup/userOfGroupChange.action?type=1",
					"data": {"groupid": $val, "creator": creator, "userid": $userid, "comid": $comid},
					"success": function(resp){
						console.log(JSON.stringify(resp));
						
					},
					"error": function(XMLHttpRequest, textStatus, errorThrown){
						alert(textStatus);
					}
				});	
			}else{
				//删除当前项
				$.ajax({
					"type": "POST",
					"dataType": 'json',
					"url": ctx+"/system/userofgroup/userOfGroupChange.action?type=0",
					"data": {"groupid": $val, "creator": creator, "userid": $userid, "comid": $comid},
					"success": function(resp){
						console.log(JSON.stringify(resp));
						
					},
					"error": function(XMLHttpRequest, textStatus, errorThrown){
						alert(textStatus);
					}
				});	
			}
		    
		};	
		
		// Enable all checkboxes.
		var dropdown = $($selector).siblings('.multiselect-container');
		$($selector + ' option').each(function() {
			var input = $('input[value="' + $(this).val() + '"]');
			input.prop('disabled', false);
			input.parent('li').addClass('disabled');
		});
	};
	
	//清空数组
	$list.length = 0;
};

</script>
		
</body>
</html>